import React, { useState } from 'react';
import { Form, Input, Select, InputNumber, Button, Space, Tabs, Switch } from 'antd';
import { Question, QuestionType, DifficultyLevel } from '@/types/question';
import SingleChoiceForm from '../../components/SingleChoiceForm';
import MultipleChoiceForm from '../../components/MultipleChoiceForm';
import TrueFalseForm from '../../components/TrueFalseForm';
import FillBlankForm from '../../components/FillBlankForm';
import CompositeQuestionForm from '../../components/CompositeQuestionForm';
import CodeBlockEditor from '../../components/CodeBlockEditor';
import TagSelector from '@/components/TagSelector';
import { tagService } from '@/services/tagService';

const { Option } = Select;
const { TextArea } = Input;

interface QuestionEditModalProps {
  question: Question;
  onSave: (question: Question) => void;
  onCancel: () => void;
}

const QuestionEditModal: React.FC<QuestionEditModalProps> = ({ question, onSave, onCancel }) => {
  const [form] = Form.useForm();
  const [hasCode, setHasCode] = useState(question.has_code || false);

  React.useEffect(() => {
    form.setFieldsValue(question);
  }, [question, form]);

  const handleSubmit = (values: any) => {
    const updatedQuestion: Question = {
      ...question,
      ...values,
      has_code: hasCode,
    };
    onSave(updatedQuestion);
  };

  // 根据题型渲染表单
  const renderQuestionTypeForm = () => {
    switch (question.type) {
      case QuestionType.SINGLE_CHOICE:
        return <SingleChoiceForm form={form} />;
      case QuestionType.MULTIPLE_CHOICE:
        return <MultipleChoiceForm form={form} />;
      case QuestionType.TRUE_FALSE:
        return <TrueFalseForm form={form} />;
      case QuestionType.FILL_BLANK:
        return <FillBlankForm form={form} />;
      case QuestionType.COMPOSITE:
        return <CompositeQuestionForm form={form} />;
      default:
        return null;
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={question}
    >
      <Tabs
        items={[
          {
            key: 'basic',
            label: '基本信息',
            children: (
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Form.Item name="title" label="题目标题">
                  <Input placeholder="题目标题（可选）" />
                </Form.Item>

                <Form.Item name="content" label="题目内容" rules={[{ required: true }]}>
                  <TextArea rows={3} placeholder="请输入题目内容" />
                </Form.Item>

                <Form.Item label="题干包含代码">
                  <Switch 
                    checked={hasCode}
                    onChange={setHasCode}
                    checkedChildren="是"
                    unCheckedChildren="否"
                  />
                </Form.Item>

                {hasCode && (
                  <CodeBlockEditor 
                    form={form}
                    codeFieldName="code_content"
                    languageFieldName="code_language"
                  />
                )}

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <Form.Item name="difficulty" label="难度">
                    <Select>
                      <Option value={1}>非常简单</Option>
                      <Option value={2}>简单</Option>
                      <Option value={3}>中等</Option>
                      <Option value={4}>困难</Option>
                      <Option value={5}>非常困难</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item name="is_active" label="是否启用" valuePropName="checked">
                    <Switch />
                  </Form.Item>
                </div>

                <Form.Item name="tags" label="标签">
                  <TagSelector 
                    value={form.getFieldValue('tags') || []}
                    onChange={(tags) => form.setFieldsValue({ tags })}
                    fetchTags={tagService.getTags}
                    addTag={tagService.addTag}
                  />
                </Form.Item>
              </Space>
            ),
          },
          {
            key: 'options',
            label: '题目选项',
            children: renderQuestionTypeForm(),
          },
          {
            key: 'explanation',
            label: '解析和提示',
            children: (
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Form.Item name="answer_explanation" label="答案解析">
                  <TextArea rows={4} placeholder="请输入答案解析" />
                </Form.Item>

                <Form.Item name="hint" label="提示">
                  <TextArea rows={2} placeholder="请输入提示信息（可选）" />
                </Form.Item>
              </Space>
            ),
          },
        ]}
      />

      <Form.Item style={{ marginTop: 24, marginBottom: 0 }}>
        <Space>
          <Button type="primary" htmlType="submit">
            保存题目
          </Button>
          <Button onClick={onCancel}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default QuestionEditModal;

